package org.mspring.mlog.action.admin;

import org.mspring.mlog.entity.Category;
import org.mspring.mlog.entity.User;
import org.mspring.mlog.service.CategoryService;
import org.mspring.nbee.orm.dao.sql.pager.PageResult;
import org.mspring.nbee.web.Action;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @author Gao Youbo
 * @since 2014-12-05 11:51
 */
@Action
@RequestMapping("/admin/category")
public class CategoryAction extends BaseAdminAction {
    private CategoryService categoryService;

    @RequestMapping("/list")
    public String list(HttpServletRequest request, HttpServletResponse response, Model model) {
        PageResult<Category> result = categoryService.list(null, null);
        model.addAttribute("result", result);
        return "/admin/category/list";
    }

    @RequestMapping("/create")
    public String create(HttpServletRequest request, HttpServletResponse response, Model model) {
        return "/admin/category/create";
    }


    @RequestMapping("/create/do")
    public String doCreate(@ModelAttribute Category category, HttpServletRequest request, HttpServletResponse response, Model model) {
        User currentUser = securityService.getCurrentUser(request);
        category.setCreateTime(new Date());
        category.setCreateUser(currentUser.getId());
        category.setCreateUserName(currentUser.getNickname());
        category.setUpdateTime(new Date());
        category.setUpdateUser(currentUser.getId());
        category.setUpdateUserName(currentUser.getNickname());
        categoryService.insert(category);
        return "redirect:/admin/category/list";
    }

    @RequestMapping("/edit")
    public String edit(HttpServletRequest request, HttpServletResponse response, Model model) {
        return "/admin/category/edit";
    }

    @RequestMapping("/edit/do")
    public String doEdit(@ModelAttribute Category category, HttpServletRequest request, HttpServletResponse response, Model model) {
        return "redirect:/admin/category/list";
    }

    @Autowired
    public void setCategoryService(CategoryService categoryService) {
        this.categoryService = categoryService;
    }
}